from git import Repo
import os
import markdown
from pathlib import Path

repo_link = "https://gitee.com/Tencent/APIJSON"
repo_name = "APIJSON"
md=f"#{repo_name}Project Analasis\n\n"
md += "---"

if os.path.isdir(repo_name):
    repo =Repo(repo_name)
else:
    print("Closing repo...")
    repo = Repo.clone_from(repo_link,repo_name)
    print("Finished clone!")

print("Loaded repo!")
repo_commits = list(repo.iter_commits())
commit_count = len(repo_commits)

print(f"{commit_count} Commits")
md += f" -{commit_count} Commits\n"

author_commits = {}
for commit in repo.iter_commits():
    author = commit.author.name
    if author not in author_commits:
        author_commits[author] = 1
    else:
        author_commits[author] +=1

author_count =len(author_commits)
print(f"{author_count} Authors" )
md += f" -{commit_count} Authors:\n"

remote =repo.remotes[0]
remote_branches = remote.refs
remote_branch_count = len(remote_branches)
print(f"{remote} Branches: ")
md += "## Branches:\n"
for branch in remote_branches:
    if branch.name == "origin/HEAD":continue
    branch_name = branch.name.split("/")[1]
    print("\t",branch.name)
    md += f" - [{branch.name}]({repo_link}/tree/{branch_name}\n"

author_commits =sorted(author_commits.items(),
                       key=lambda data:data[1],reverse=True)
print("Top 10 Authors :")
md += "## Top 10 Authors :\n"

for i in range(10):
    author = author_commits[i][0].strip(" ")
    commits = author_commits[i][0]
    print("\t",f"{author}:{commits} commits")
    md += (f"{i+1}. [{author}](https://gitee.com/{author}):{commits} commits\n")

Path("report.md").write_text(md)